const nickP = document.querySelector('.nickP')
const loginDiv = document.querySelector('.login')
const nickDiv = document.querySelector('.nick')
const logout = document.querySelector('.logout')

// 先获取存储的id和login 如果没有的话代表没有登录过,先登录
const id = window.localStorage.getItem('id')
const login = window.localStorage.getItem('login')
const nick = window.localStorage.getItem('nick')
function testLogin() {
  if (!login) {
    window.localStorage.setItem('url', 'cart')
    window.location.href = './login.html'
    return
  }
}
nickP.innerText = 'hello ' + nick

$('.nick').mouseover(function () {
  $('.nick_box').stop().slideDown(500, 'linear')
})
$('.nick').mouseleave(function () {
  $('.nick_box').stop().slideUp(500, 'linear')
})

// 给帮助中心添加鼠标移入事件,移入时给盒子添加类名让其显示
$('.help').mouseover(function () {
  $('.help_box').stop().slideDown(300, 'linear')
})
$('.help').mouseout(function () {
  $('.help_box').stop().slideUp(300, 'linear')
})

// 注销点击事件
logout.onclick = () => {
  window.localStorage.removeItem('id')
  window.localStorage.removeItem('login')
  window.localStorage.removeItem('nick')
  window.location.href='./index.html'
}

// 二级菜单跳转列表页
const nav_box = document.querySelectorAll('.nav_box>li')
nav_box.forEach(item => {
  item.onclick = function () {
    window.location.href = './list.html'
  }
})
// 返回首页
const go_index = document.querySelector('.go_index')
go_index.onclick = () => {
  window.location.href = './index.html'
}

// 先将点击的数据放在浏览器中,然后购物车渲染的时候从中拿到id找到后进行渲染
let cart = window.localStorage.getItem('cart')
let res = JSON.parse(cart)

const content = document.querySelector('.content')

// 整体修改cart里边的值,修改以后重新获取

bindHtml()
function bindHtml() {
  cart = window.localStorage.getItem('cart')

  let tNum = 0
  let tPrice = 0
  let selectAll = 0
  res.forEach(item => {
    if (item.check === true) {
      selectAll++
      tNum += item.cart_number - 0
      tPrice += (item.defaultPrice - 0) * tNum
    }
  })


  let str = ''

  str = `
    <div class="top">
    <ul class="top_box">
      <li>
        <label class="all">
          <input class="check_all" type="checkbox" data-type="${res.length === selectAll ? true : false}" type="checkbox" ${res.length === selectAll ? 'checked' : ''} >
          <span>全选</span>
        </label>
      </li>
      <li class="info">商品信息</li>
      <li class="price_t">单价</li>
      <li class="num">数量</li>
      <li class="p_price">价格小计</li>
    </ul>
  </div>
    `

  res.forEach(item => {
    str += `
        
      <ul class="cartBox">
        <li>
          <div class="select">
            <input data-id="${item.id}" type="checkbox" class="check_one" ${item.check ? 'checked' : ''}>
          </div>
          <div class="show">
            <img src="${item.productImages[0]}" alt="">
          </div>
          <div class="title">
          ${item.productName}
          </div>
          <div class="price">
            ￥ ${(item.defaultPrice).toFixed(2)}
          </div>
          <div class="number">
            <button class="reduce">-</button>
            <input class="count" type="text" data-id="${item.id}" data-num="${item.categoryRankNo}" value="${item.cart_number - 0}">
            <button class="add">+</button>
          </div>
          <div class="subprice">
            ￥ ${((item.defaultPrice) * item.cart_number).toFixed(2)}
          </div>
          <div class="del">
            <button data-id="${item.id}" class="del_btn">删除</button>
          </div>
        </li>
      </ul>
      
        `
  })
  str += `
    <div class="bottom">
        <p class="totalNum">
          购买总数: ${tNum}
        </p>
        <p class="btn">
          <button class="del_check">删除所有已选中</button>
          <button class="del_all">清空购物车</button>
          <button data-money="${tPrice.toFixed(2)}" class="pay">去结算</button>
          <button class="bk_list">继续去选购</button>
        </p>
        <p class="totalPrice">
          总价格 : ${tPrice.toFixed(2)}
        </p>
      </div>
    `

  content.innerHTML = str
}
// 事件委托
const check_one = document.querySelector('.check_one')
content.addEventListener('click', e => {
  e = e || window.event
  const target = e.target || e.srcElement
  if (target.className === 'check_all') {
    const type = target.checked
    console.log(type)
    res.forEach(item => {
      item.check = type
    })
    bindHtml()
  }

  // 单选按钮
  if (target.className === 'check_one') {
    let a = target.checked
    let id = target.dataset.id
    res.forEach(item => {
      if (item.id === id) {
        item.check = a
      }
    })
    window.localStorage.setItem('cart', JSON.stringify(res))
    bindHtml()
  }
  // 数量增减
  if (target.className === 'reduce') {
    let num = target.nextElementSibling.value - 0
    const goodsId = target.nextElementSibling.dataset.id
    if (num <= 1) return
    num--
    res.forEach(item => {
      if (item.id === goodsId) {
        item.cart_number = num
      }
    })
    bindHtml()
  }
  if (target.className === 'add') {
    let num = target.previousElementSibling.value - 0
    let sum = target.previousElementSibling.dataset.num - 0
    const goodsId = target.previousElementSibling.dataset.id
    if (num >= sum) return
    num++
    res.forEach(item => {
      if (item.id === goodsId) {
        item.cart_number = num
      }
    })
    bindHtml()
  }
  // 删除单个
  if (target.className === 'del_btn') {
    const goodsId = target.dataset.id
    res = res.filter(function (item) { return item.id !== goodsId })
    window.localStorage.setItem('cart', JSON.stringify(res))
    bindHtml()
  }

  // 删除已选中
  if (target.className === 'del_check') {
    res = res.filter(function (item) { return item.check === false })
    window.localStorage.setItem('cart', JSON.stringify(res))
    bindHtml()
  }

  // 清空购物车
  if (target.className === 'del_all') {
    res = []
    window.localStorage.setItem('cart', JSON.stringify(res))
    bindHtml()

  }
  if (target.className === 'pay') {
    const money = target.dataset.money
    const bool = window.confirm(`您需要支付${money}元,点击确定去支付 ^_^`)
    if (bool) {
      res = res.filter(function (item) { return item.check === false })
      window.localStorage.setItem('cart', JSON.stringify(res))
      bindHtml()
    }
  }
  if (target.className === 'bk_list') {
    window.location.href = './list.html'
  }

})
content.addEventListener('change', e => {
  e = e || window.event
  const target = e.target || e.srcElement
  if (target.className === 'count') {
    let num = target.value - 0
    const goodsId = target.dataset.id
    res.forEach(item => {
      if (item.id === goodsId && num <= item.categoryRankNo) {
        item.cart_number = num
      }
    })
    window.localStorage.setItem('cart', JSON.stringify(res))
    bindHtml()
  }
})

